package com.zl.tby.controller;

import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.icc.*;
import com.zl.tby.model.TbyCarRecord;
import com.zl.tby.service.ITbyCarRecordService;
import com.zl.tby.service.ITbyConfigInfoService;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.validation.annotation.Valid;
import org.noear.wood.utils.StringUtils;

import java.util.*;

/**
 * @author changpeng
 * @version 1.0
 * @since 2024/9/5 9:20
 */
@Valid
@Controller
@Mapping("/icc")
public class IccController {

    /*@Inject("${icc.ws-in-url}")
    private String wsInUrl;
    @Inject("${icc.ws-out-url}")
    private String wsOutUrl;
    @Inject("${icc.http-in-url}")
    private String httpInUrl;
    @Inject("${icc.http-out-url}")
    private String httpOutUrl;
    @Inject("${icc.check-source}")
    private String checkSource;

    @Mapping(value = "/config", method = MethodType.GET)
    public R<?> config(String ip) {
        boolean inNet = false;
        if (StringUtils.isNotEmpty(ip) && StringUtils.isNotEmpty(checkSource)) {
            if (ip.indexOf(checkSource) > -1) {
                inNet = true;
            } else if(ip.equals("localhost") || ip.equals("127.0.0.1")) {
                inNet = true;
            }
        }
        Map<String, String> map = new HashMap<>(2);
        map.put("ws", inNet ? wsInUrl : wsOutUrl);
        map.put("http", inNet ? httpInUrl : httpOutUrl);
        return R.ok(map);
    }*/

    @Inject
    private ITbyConfigInfoService configInfoService;

    /**
     * 获取视频地址
     * @param deviceCode：设备编码
     * @return 结果
     * @throws Exception 异常
     */
    @Mapping(value = "/url", method = MethodType.GET)
    public Object getVideoUrl(String deviceCode) throws Exception {
        R<IccDeviceInfo> device = IccUtil.getDeviceInformation(deviceCode);
        if (device.getCode() == 0) {
            String channelId = device.getData().getChannelId();
            if (StringUtils.isNotEmpty(channelId)) {
                R<IccVideoInfo> video = IccUtil.getVideoUrl(channelId, "1", "1");
                if (video.getCode() != 0) {
                    return video;
                }
                if (video.getData().getUrl() == null) {
                    return R.failed("未获取到视频地址");
                }
                Map<String, String> result = new HashMap<>(0);
                result.put("channelId", channelId);
                result.put("deviceName", device.getData().getDeviceName());
                result.put("url", video.getData().getUrl());
                result.put("lon", device.getData().getLon());
                result.put("lat", device.getData().getLat());
                return R.ok(result);
            }
            return R.failed("获取视频通道异常");
        }
        return R.failed(device.getMsg());
    }

    /**
     * 设备列表
     * @param pageSize: 获取数量
     * @param deviceCategory：大类，传0为不根据大类进行查询
     * @return 列表
     * @throws Exception 异常信息
     */
    @Mapping(value = "/deviceList", method = MethodType.GET)
    public R<List<TbyDeviceInfo>> deviceList(Integer pageSize, Integer deviceCategory, String ips) throws Exception {
        List<IccDeviceInfo> deviceList = IccUtil.deviceList(pageSize, deviceCategory, ips).getData();
        List<TbyDeviceInfo> entityList = new ArrayList<>();
        for (IccDeviceInfo device : deviceList) {
            TbyDeviceInfo tby = TbyDeviceInfo.createByIccDeviceInfo(device);
            if (tby != null) {
                entityList.add(tby);
            }
        }
        return R.ok(entityList);
    }

    /**
     * 设备在线离线统计
     * @return 结果
     * @throws Exception 异常
     */
    @Mapping(value = "/deviceStatistic", method = MethodType.GET)
    public R<Map<String, Long>> deviceStatistic() throws Exception {
        Map<String, String> map = this.configInfoService.getValueByCode("snapshotCameraIp,alertCameraIp,globalColorMachine,highAltitudeWideAngle");
        List<IccDeviceInfo> deviceList = IccUtil.deviceList(500, 0, null).getData();
        Map<String, Long> result = new HashMap<>(0);
        // 抓拍摄像机
        String zpIp = ToolsUtil.addPreAndFix(map.get("snapshotCameraIp"), ",", ",", "");
        long zpTotal = 10, zpOn = 0, zpOff = 0;
        // 警戒摄像机
        String jjIp = ToolsUtil.addPreAndFix(map.get("alertCameraIp"), ",", ",", "");
        long jjTotal = 49, jjOn = 0, jjOff = 0;
        // 全彩球机
        String qcIp = ToolsUtil.addPreAndFix(map.get("globalColorMachine"), ",", ",", "");
        long qcTotal = 11, qcOn = 0, qcOff = 0;
        // 高空广角摄像机
        String gjIp = ToolsUtil.addPreAndFix(map.get("highAltitudeWideAngle"), ",", ",", "");
        long qjTotal = 1, qjOn = 0, qjOff = 0;

        if (deviceList != null) {
            for (IccDeviceInfo device : deviceList) {
                if (device.getIsOnline().compareTo(1) == 0) {
                    if (zpIp.indexOf("," + device.getDeviceIp() + ",") > -1) { zpOn++; }
                    else if (jjIp.indexOf("," + device.getDeviceIp() + ",") > -1) { jjOn++; }
                    else if (qcIp.indexOf("," + device.getDeviceIp() + ",") > -1) { qcOn++; }
                    else if (gjIp.indexOf("," + device.getDeviceIp() + ",") > -1) { qjOn++; }
                }
                /*if (device.getIsOnline().compareTo(0) == 0) {
                    if (zpIp.indexOf("," + device.getDeviceIp() + ",") > -1) { zpTotal++; zpOff++; }
                    else if (jjIp.indexOf("," + device.getDeviceIp() + ",") > -1) { jjTotal++; jjOff++; }
                    else if (qcIp.indexOf("," + device.getDeviceIp() + ",") > -1) { qcTotal++; qcOff++; }
                    else if (gjIp.indexOf("," + device.getDeviceIp() + ",") > -1) { qjTotal++; qjOff++; }
                } else if (device.getIsOnline().compareTo(1) == 0) {
                    if (zpIp.indexOf("," + device.getDeviceIp() + ",") > -1) { zpTotal++; zpOn++; }
                    else if (jjIp.indexOf("," + device.getDeviceIp() + ",") > -1) { jjTotal++; jjOn++; }
                    else if (qcIp.indexOf("," + device.getDeviceIp() + ",") > -1) { qcTotal++; qcOn++; }
                    else if (gjIp.indexOf("," + device.getDeviceIp() + ",") > -1) { qjTotal++; qjOn++; }
                }*/
            }
        }
        jjOff = jjTotal - jjOn;
        qcOff = qcTotal - qcOn;
        qjOff = qjTotal - qjOn;
        zpOff = zpTotal - zpOn;
        result.put("jjTotal", jjTotal); result.put("jjOn", jjOn); result.put("jjOff", jjOff);
        result.put("qcTotal", qcTotal); result.put("qcOn", qcOn); result.put("qcOff", qcOff);
        result.put("qjTotal", qjTotal); result.put("qjOn", qjOn); result.put("qjOff", qjOff);
        result.put("zpTotal", zpTotal); result.put("zpOn", zpOn); result.put("zpOff", zpOff);
        return R.ok(result);
    }

    /**
     * 方向控制
     * @param channelId：视频通道编码
     * @param direct：方向：1=上，2=下，3=左，4=右，5=左上，6=左下，7=右上，8=右下
     * @param speed：速度，1 - 8
     * @param command： 0=停止, 1=开启
     * @param inNet: 0=外网 1=内网
     * @return
     */
    @Mapping(value = "/ctrl_direct", method = MethodType.GET)
    public R<IccResponse> ctrlDirect(String channelId, String direct, String speed, String command, String inNet) {
        return IccUtil.ctrlDirect(channelId, direct, speed, command, inNet);
    }

    /**
     * 变焦等控制
     * @param channelId: 视频通道编码
     * @param operateType： 操作类型：1=变倍，2=变焦，3=光圈
     * @param direct： 方向：1=增加，2=减小
     * @param step： 转动速度
     * @param command： 命令：0=停止动作，1=开启动作
     * @return
     */
    @Mapping(value = "/ctrl_camera", method = MethodType.GET)
    public R<IccResponse> ctrlCamera(String channelId, String operateType, String direct, String step, String command, String inNet) {
        return IccUtil.ctrlCamera(channelId, operateType, direct, step, command, inNet);
    }

    @Mapping(value = "/ctrl_cruises", method = MethodType.GET)
    public R<IccCruisesResult> ctrlCruises(String channelId) {
        return IccUtil.getCruisesLine(channelId);
    }



    @Mapping(value = "/demo", method = MethodType.GET)
    public Object demo() throws Exception {
        /*Date startDate = ToolsUtil.dateString2Util("2024-09-18 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endDate = ToolsUtil.dateString2Util("2024-09-18 23:59:59", "yyyy-MM-dd HH:mm:ss");
        return IccUtil.searchCarRecordList(1, 1000, startDate, endDate);*/
        return null;
    }

    //@Mapping(value = "/run", method = MethodType.GET)
    public Object run() throws Exception {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                ITbyCarRecordService service = Solon.context().getBean(ITbyCarRecordService.class);
                Date start = ToolsUtil.dateString2Util("2024-01-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
                Date end = ToolsUtil.dateString2Util("2024-09-19 00:00:00", "yyyy-MM-dd HH:mm:ss");
                while (start.getTime() < end.getTime()) {
                    int page = 1;
                    int pageNum = 200;
                    Date endDate = new Date(start.getTime() + (1000 * 60 * 60 * 24));
                    while(true) {
                        try {
                            System.out.println("page: " + page);
                            System.out.println("pageNum: " + pageNum);
                            System.out.println("startDate: " + ToolsUtil.dateUtil2String(start, "yyyy-MM-dd HH:mm:ss"));
                            System.out.println("endDate: " + ToolsUtil.dateUtil2String(endDate, "yyyy-MM-dd HH:mm:ss"));
                            R<IccResponse<IccPageVo<IccCarRecord>>> r = IccUtil.searchCarRecordList(page, pageNum, start, endDate);
                            if (r.getData().getCode().compareTo(1000) != 0) {
                                break;
                            }
                            List<IccCarRecord> list = r.getData().getData().getList();
                            if (list == null || list.size() == 0) {
                                break;
                            }
                            List<TbyCarRecord> entityList = new ArrayList<>();
                            for (IccCarRecord data : list) {
                                entityList.add(IccCarRecord.convert(data));
                            }
                            service.addBatch(entityList);
                            page++;
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    start = endDate;
                }
            }
        });
        t.start();
        return null;
    }
}
